package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.param.chat.EditChatNickName;
import com.fzg.common.model.param.chat.SendMessageParam;
import com.fzg.common.model.result.chat.ChatContent;
import com.fzg.common.tool.JwtUtil;
import com.fzg.common.tool.ToolForDateTime;
import com.fzg.entity.Chat;
import com.fzg.entity.Tag;
import com.fzg.entity.User;
import com.fzg.mapper.ChatMapper;
import com.fzg.mapper.TagMapper;
import com.fzg.mapper.UserMapper;
import com.fzg.service.ChatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2022-07-12
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements ChatService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ChatMapper chatMapper;

    @Override
    public ResponseWrapper queryChatRecordInfo(HttpServletRequest request, Integer userAid) {
        // 返回结果
        HashMap<String, Object> result = new HashMap<>();

        // 对方用户的用户昵称
        User chatUser = userMapper.selectById(userAid);
        List<Chat> chats2 = chatMapper.selectList(new LambdaQueryWrapper<Chat>().eq(Chat::getReceiveUserAid, userAid));

        if (chats2.size() > 0) {
            if (chats2.get(0).getReceivedUserNickName().equals("") || chats2.get(0).getReceivedUserNickName() == null) {
                result.put("userNickName", chatUser.getNickName() == null ? chatUser.getUserName() : chatUser.getNickName());
            } else {
                result.put("userNickName", chats2.get(0).getReceivedUserNickName());
            }
        } else {
            result.put("userNickName", chatUser.getNickName() == null ? chatUser.getUserName() : chatUser.getNickName());
        }

        // 当前登陆的用户的头像
        User currentLoginUser = userMapper.selectById(JwtUtil.getTokenId(request.getHeader("token")));
        if (currentLoginUser.getAvatar() == null) {
            if (currentLoginUser.getGender().equals(1)) {
                result.put("currentUserAvatarUrl", "https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/user/avatar_userbg/1656988498000.jpg");
            } else {
                result.put("currentUserAvatarUrl", "https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/user/avatar_userbg/girl_avatar01.jpg");
            }
        } else {
            result.put("currentUserAvatarUrl", currentLoginUser.getAvatar());
        }

        // 对方头像
        if (chatUser.getAvatar() == null) {
            if (chatUser.getGender().equals(1)) {
                result.put("chatUserAvatarUrl", "https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/user/avatar_userbg/1656988498000.jpg");
            } else {
                result.put("chatUserAvatarUrl", "https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/user/avatar_userbg/girl_avatar01.jpg");
            }
        } else {
            result.put("chatUserAvatarUrl", chatUser.getAvatar());
        }

        // 匹配度（直接在90到97之间随机取数）
        Random rand = new Random();
        int matchProcess = rand.nextInt(8) + 90;
        result.put("matchProcess", matchProcess);

        // 双方都喜欢的tags
        List<Tag> currentUserTagList = tagMapper.selectList(new LambdaQueryWrapper<Tag>().eq(Tag::getUserAid, currentLoginUser.getAid()));
        List<Tag> taTagList = tagMapper.selectList(new LambdaQueryWrapper<Tag>().eq(Tag::getUserAid, chatUser.getAid()));
        ArrayList<Tag> bothTags = new ArrayList<>();
        for (Tag tag : currentUserTagList) {
            for (Tag tag1 : taTagList) {
                if (tag.getName().equals(tag1.getName())) {
                    bothTags.add(tag1);
                }
            }
        }
        StringBuffer bothTagString = new StringBuffer();
        for (Tag bothTag : bothTags) {
            bothTagString.append(bothTag.getName());
            bothTagString.append("、");
        }
        if (bothTagString.length() > 1) {
            bothTagString.deleteCharAt(bothTagString.length() - 1);
            result.put("bothTags", bothTagString);
        } else {
            result.put("bothTags", "");
        }


        // ta的tags
        StringBuffer taTagString = new StringBuffer();
        for (Tag tag : taTagList) {
            taTagString.append(tag.getName());
            taTagString.append("、");
        }
        if (taTagString.length() > 1) {
            taTagString.deleteCharAt(taTagString.length() - 1);
            result.put("taTags", taTagString);
        } else {
            result.put("taTags", "");
        }


        // 聊天的内容
        ArrayList<ChatContent> chatContents = new ArrayList<>();
        // 自己发送过去的消息
        List<Chat> chats = chatMapper.selectList(new LambdaQueryWrapper<Chat>().eq(Chat::getSendUserAid, currentLoginUser.getAid()).eq(Chat::getReceiveUserAid, chatUser.getAid()));
        for (Chat chat : chats) {
            ChatContent chatContent = new ChatContent();
            chatContent.setChat(chat);
            if (currentLoginUser.getAvatar() == null) {
                if (currentLoginUser.getGender().equals(1)) {
                    chatContent.setAvatar("https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/user/avatar_userbg/1656988498000.jpg");
                } else {
                    chatContent.setAvatar("https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/user/avatar_userbg/girl_avatar01.jpg");
                }
            } else {
                chatContent.setAvatar(currentLoginUser.getAvatar());
            }
            chatContent.setTime(ToolForDateTime.LocalDateTimeToString(chat.getCreateTime()));
            chatContents.add(chatContent);
        }
        // 对方发送来的消息
        List<Chat> chats1 = chatMapper.selectList(new LambdaQueryWrapper<Chat>().eq(Chat::getSendUserAid, chatUser.getAid()).eq(Chat::getReceiveUserAid, currentLoginUser.getAid()));
        ArrayList<ChatContent> chatContents1 = new ArrayList<>();
        for (Chat chat : chats1) {
            ChatContent chatContent = new ChatContent();
            chatContent.setChat(chat);
            if (chatUser.getAvatar() == null) {
                if (chatUser.getGender().equals(1)) {
                    chatContent.setAvatar("https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/user/avatar_userbg/1656988498000.jpg");
                } else {
                    chatContent.setAvatar("https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/user/avatar_userbg/girl_avatar01.jpg");
                }
            } else {
                chatContent.setAvatar(chatUser.getAvatar());
            }
            chatContent.setTime(ToolForDateTime.LocalDateTimeToString(chat.getCreateTime()));
            chatContents1.add(chatContent);
        }

        ArrayList<ChatContent> chatContents2 = new ArrayList<>();
        chatContents2.addAll(chatContents);
        chatContents2.addAll(chatContents1);
        chatContents2.sort(Comparator.comparing(ChatContent::getTime));
        result.put("contacts", chatContents2);

        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 通过用户aid修改聊天记录页面里面的对方用户昵称
     *
     * @param request 参数
     * @param param 参数
     * @return ResponseWrapper
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper editChatUserNickName(HttpServletRequest request, EditChatNickName param) {
        List<Chat> chats = chatMapper.selectList(new LambdaQueryWrapper<Chat>().eq(Chat::getSendUserAid, JwtUtil.getTokenId(request.getHeader("token"))).eq(Chat::getReceiveUserAid, param.getUserAid()));
        for (Chat chat : chats) {
            chat.setReceivedUserNickName(param.getUserNickName());
            chatMapper.updateById(chat);
        }
        return ResponseWrapper.markSuccess();
    }

    /**
     * 发送给对方消息
     *
     * @param request 参数
     * @param param 参数
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper sendMessageToChatObject(HttpServletRequest request, SendMessageParam param) {

        // 自己的aid
        Integer currentLoginUserAid = JwtUtil.getTokenId(request.getHeader("token"));

        // 对方用户
        User user = userMapper.selectById(param.getUserAid());

        chatMapper.insert(new Chat() {{
            setSendUserAid(currentLoginUserAid);
            setReceiveUserAid(param.getUserAid());
            setContent(param.getNewMessage());
            if (chatMapper.selectList(new LambdaQueryWrapper<Chat>().eq(Chat::getSendUserAid, currentLoginUserAid).eq(Chat::getReceiveUserAid, user.getAid())).size() > 0) {
                setReceivedUserNickName(chatMapper.selectList(new LambdaQueryWrapper<Chat>().eq(Chat::getSendUserAid, currentLoginUserAid).eq(Chat::getReceiveUserAid, user.getAid())).get(0).getReceivedUserNickName());
            } else {
                setReceivedUserNickName(user.getNickName() == null ? user.getUserName() : user.getNickName());
            }
        }});
        return ResponseWrapper.markSuccess();
    }
}
